package com.letoken.platform.app.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.letoken.platform.app.consumer.FundConsumer;
import com.letoken.platform.app.consumer.FundReleaseConsumer;
import com.letoken.platform.app.service.*;
import com.letoken.platform.pub.annotation.auth.NotAuthorization;
import com.letoken.platform.pub.constant.RedisKeyConstant;
import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import com.letoken.platform.pub.enums.LetokenTokenTypeEnum;
import com.letoken.platform.pub.enums.TokenTransactionStatusEnum;
import com.letoken.platform.pub.enums.TokenTransactionTypeEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.req.PageData;
import com.letoken.platform.pub.req.PageReq;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.repo.admin.dao.AdminFundConfigMapper;
import com.letoken.platform.repo.admin.po.AdminFundConfig;
import com.letoken.platform.repo.app.dao.*;
import com.letoken.platform.repo.app.po.*;
import com.letoken.platform.repo.app.redis.RedisConfig;
import com.letoken.platform.repo.app.req.user.FundTransferReq;
import com.letoken.platform.repo.app.req.user.UserLevelReq;
import com.letoken.platform.repo.mall.dao.AppMallAmbassadorMapper;
import com.letoken.platform.repo.mall.po.AppMallAmbassador;
import com.letoken.platform.repo.utlis.PageDataUtil;
import com.letoken.platform.repo.utlis.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2023-08-04
 */
@RestController
@RequestMapping("/appFundInfoController")
@Slf4j
public class AppFundInfoController {
    @Resource
    AdminFundConfigMapper adminFundConfigMapper;

    @Resource
    AppUserWalletMapper appUserWalletMapper;

    @Autowired
    AppFundInfoService appFundInfoService;

    @Autowired
    AppUserWalletService appUserWalletService;
    @Resource
    AppFundInfoMapper appFundInfoMapper;

    @Resource
    AppFundLevelInfoMapper appFundLevelInfoMapper;

    @Resource
    AppFundRankingMapper appFundRankingMapper;

    @Resource
    AppFundRankInfoMapper appFundRankInfoMapper;

    @Autowired
    AppUserLampService appUserLampService;

    @Resource
    AppUserLampMapper appUserLampMapper;

    @Resource
    AdminLampConfigMapper adminLampConfigMapper;

    @Resource
    AppFundV2InfoService appFundV2InfoService;
    @Resource
    private RedisConfig redisConfig;

   // @Cacheable(cacheNames = RedisKeyConstant.FUND_CONFIG, key = "'fundConfig'", sync = true)
    @GetMapping("/getFundConfig")
    public ApiResponse<Map<String,Object>> getFundConfig() {
        Map<String,Object> map = new HashMap<>();
        map.put("min",100);
        map.put("get",2);
        return ApiResponse.create(map);
    }

    private void checkout(FundTransferReq req){
        if ( req.getAmount().compareTo(BigDecimal.ONE) < 0){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_054);
        }
        //Integer balanceId = appBalanceWalletMapper.getIdByUserId(LetokenTokenTypeEnum.LET.getId(),req.getUserId());
        Integer walletId = appUserWalletMapper.checkoutTokenIdAndUserId(LetokenTokenTypeEnum.LET.getId(), req.getUserId());
        if (/*ObjectUtils.isEmpty(balanceId) ||*/ ObjectUtils.isEmpty(walletId)){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_051);
        }
        //req.setBalanceId(balanceId);
        req.setWalletId(walletId);
    }


    /*@PostMapping("/transferIn")
    public ApiResponse transferIn(@Validated @RequestBody FundTransferReq req) {


        if (new BigDecimal(req.getAmount().intValue()).compareTo(req.getAmount())!=0){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_055);
        }
        QueryWrapper<AdminFundConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",req.getFundId());
        AdminFundConfig adminFundConfig = adminFundConfigMapper.selectOne(queryWrapper);
        if(adminFundConfig == null || adminFundConfig.getMin().compareTo(req.getAmount())>0){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_057);
        }
        req.setUserId(WebUtils.getUserId());
        req.setAdminFundConfig(adminFundConfig);
        checkout(req);
        BigDecimal bigDecimal = appFundInfoMapper.getFundAmountByType(req.getUserId(),req.getFundId());
        if(adminFundConfig.getMaxFund().compareTo(bigDecimal.add(req.getAmount()))<0){
            throw new ApiServiceException("发行失败,超过发行上限");
        }
        appFundInfoService.transferIn(req);
        return ApiResponse.create();
    }*/

    /**
     * 基金发行
     * @param req
     * @return
     */
    @PostMapping("/transferIn")
    public ApiResponse transferIn(@Validated @RequestBody FundTransferReq req) {


        if (new BigDecimal(req.getAmount().intValue()).compareTo(req.getAmount())!=0){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_055);
        }

        QueryWrapper<AdminFundConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",req.getFundId());
        AdminFundConfig adminFundConfig = adminFundConfigMapper.selectOne(queryWrapper);
        if(new BigDecimal("100").compareTo(req.getAmount())>0){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_057);
        }
        req.setUserId(WebUtils.getUserId());
        checkout(req);

        String key = String.format(RedisKeyConstant.UPDATE_FUND_INFO,req.getUserId());

        RedissonClient redissonClient = redisConfig.getRedisson();
        RLock rlock = redissonClient.getLock(key);
        try {
            rlock.lock(20, TimeUnit.SECONDS);
            appFundInfoService.transferIn(req);
        }finally {
        if (rlock != null && rlock.isHeldByCurrentThread()) {
            rlock.unlock();
        }
    }
        return ApiResponse.create();
    }

    public static  final   List<Integer> list = Arrays.asList(16475871, 16478014,16475697,16481680,16481682,16486995,16481683,16501430);

    /**
     * 赎回基金发型
     * @param fundId
     * @return
     */
   // @GetMapping("/updateFundInfo")
    public ApiResponse updateFundInfo(@RequestParam("fundId") Integer fundId) {
       // if (!list.contains(WebUtils.getUserId())) throw new ApiServiceException("赎回暂时关闭") ;
        QueryWrapper<AppFundInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",fundId).eq("user_id",WebUtils.getUserId()).eq("type",1).eq("state",1);
        AppFundInfo adminFundConfig = appFundInfoService.getOne(queryWrapper);
        if(adminFundConfig == null || adminFundConfig.getExpirationTime().compareTo(LocalDateTime.now()) > 0){
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_MALL_SMS_056);
        }
        adminFundConfig.setType(2);
        appFundInfoService.updateById(adminFundConfig);

        AppFundDetail appFundDetail = new AppFundDetail();
        appFundDetail.setUserId(adminFundConfig.getUserId());
        appFundDetail.setType(5);
        appFundDetail.setAmount(adminFundConfig.getFund());
        appFundDetail.setCreateTime(LocalDateTime.now());
        appFundDetail.insert();

        AppUserAssetsHistory assetHistory = new AppUserAssetsHistory();
        assetHistory.setUserId(WebUtils.getUserId());
        assetHistory.setType(TokenTransactionTypeEnum.FUND_SELL.getValue());
        assetHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
        assetHistory.setTokenId(LetokenTokenTypeEnum.LET.getId());
        assetHistory.setAmount(adminFundConfig.getFund());
        assetHistory.setSn(adminFundConfig.getId().toString());
        assetHistory.setCreateTime(LocalDateTime.now());
        assetHistory.insert();

        int updateWallet = appUserWalletService.updateUserAmountByUserIDandCoin(adminFundConfig.getFund(), new BigDecimal("0"),BigDecimal.ZERO, adminFundConfig.getUserId(), LetokenTokenTypeEnum.LET.getId());
        if (updateWallet == 0) {
            throw new ApiServiceException(500, "mint失败，请稍后再试！");
        }
        try {
            AppUserAssetsHistory updateAssetHistory = new AppUserAssetsHistory();
            updateAssetHistory.setBalance(appUserWalletMapper.getAvailableBalance(assetHistory.getTokenId(), assetHistory.getUserId()));
            updateAssetHistory.setId(assetHistory.getId());
            assetHistory.updateById();
        }catch (Exception e){
            log.error("更新余额失败 id{} eMsg{}", assetHistory.getId(), e.getMessage());
        }


        return ApiResponse.create();
    }

   // @GetMapping ("/getFundAmountByType")
    public ApiResponse getFundAmountByType(@RequestParam("fundType") Integer fundType) {
        return ApiResponse.create(appFundInfoMapper.getFundAmountByType(WebUtils.getUserId(),fundType));
    }


    /**
     * 获取发型记录  旧版
     * @param
     * @return
     */
    //@PostMapping  ("/getFundInfoList")
   /* public ApiResponse<PageData<AppFundInfo>> getFundInfoList(@Validated @RequestBody PageReq req) {
        Page<AppFundInfo> page = new Page<>(req.getPage(), req.getSize());
        Page<AppFundInfo> page1 = appFundInfoMapper.getFundInfoList(WebUtils.getUserId(),page);
        List<AppFundInfo> appFundInfos = new ArrayList<>();
        for(AppFundInfo appFundInfo : page1.getRecords()){
            if(appFundInfo.getState().equals(2) && appFundInfo.getExpirationTime().compareTo(LocalDateTime.now()) < 0){
                continue;
            }
            appFundInfos.add(appFundInfo);
        }
        page1.setRecords(appFundInfos);
        return ApiResponse.create(PageDataUtil.getPageData(page1));
    }*/
    /**
     * 获取发型记录  v2
     * @param
     * @return
     */
    @PostMapping  ("/getFundInfoList")
    public ApiResponse<AppFundV2Info> getFundInfoList() {
        QueryWrapper<AppFundV2Info> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("user_id", WebUtils.getUserId());
        return ApiResponse.create(appFundV2InfoService.getOne(accountQueryWrapper));
    }

    @PostMapping ("/getFundDetailoList")
    public ApiResponse<PageData<AppFundV2Detail>> getFundDetailoList(@Validated @RequestBody PageReq req) {
        Page<AppFundV2Detail> page = new Page<>(req.getPage(), req.getSize());
        return ApiResponse.create(PageDataUtil.getPageData(appFundInfoMapper.getFundDetailoList(WebUtils.getUserId(),page)));
    }

    @GetMapping ("/getLvel")
    public ApiResponse getLvel() {
        AppFundLevelInfo appFundLevelInfo = appFundLevelInfoMapper.selectById(WebUtils.getUserId());
        if(appFundLevelInfo == null){
            AppFundLevelInfo appFundLevelInfo1 = new AppFundLevelInfo();
            appFundLevelInfo1.setCreateTime(LocalDateTime.now());
            appFundLevelInfo1.setUserId(WebUtils.getUserId());
            appFundLevelInfo1.setLevel(0);
            appFundLevelInfo1.insert();
        }
        return ApiResponse.create(appFundLevelInfo==null?0:appFundLevelInfo.getLevel());
    }

    @GetMapping ("/rankingList")
    public ApiResponse rankingList(@RequestParam("type")Integer type) {
        LocalDateTime now = LocalDateTime.now();
        String threshold = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(threshold, formatter);
        String startTime;
        String endTime;
        List<AppFundRanking> list;
        if(type.equals(1)) {
            if(now.isAfter(dateTime) == true){
                startTime = threshold;
                now = now.plusDays(1);
                endTime = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
            }else{
                endTime = threshold;
                dateTime = dateTime.plusDays(-1);
                startTime = dateTime.getYear()+"-"+dateTime.getMonthValue()+"-"+dateTime.getDayOfMonth()+" 18:00:00";;
            }
            list = appFundRankingMapper.getAppFundRanking1(startTime, endTime);
        } else{
            LocalDateTime start = appFundRankingMapper.time(2);
            LocalDateTime end = appFundRankingMapper.time(2).plusDays(7);
            list =appFundRankingMapper.getAppFundRanking7(start.getYear()+"-"+start.getMonthValue()+"-"+start.getDayOfMonth()+" 18:00:00",end.getYear()+"-"+end.getMonthValue()+"-"+end.getDayOfMonth()+" 18:00:00");
          }
        return ApiResponse.create(list);
    }

    @GetMapping ("/currentUser")
    public ApiResponse currentUser(@RequestParam("type")Integer type) {
        AppFundRanking appFundRanking = new AppFundRanking();
        if (type.equals(1)) {
            LocalDateTime now = LocalDateTime.now();
            String threshold = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(threshold, formatter);
            String startTime;
            String endTime;
            if(now.isAfter(dateTime) == true){
                startTime = threshold;
                now = now.plusDays(1);
                endTime = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
            }else{
                endTime = threshold;
                dateTime = dateTime.plusDays(-1);
                startTime = dateTime.getYear()+"-"+dateTime.getMonthValue()+"-"+dateTime.getDayOfMonth()+" 18:00:00";;
            }
            log.info("~~~~~~~~~~~~~~~~~~~~~~~~~"+startTime+"~~~~~~~~~~~~~~"+endTime);
        appFundRanking = appFundRankingMapper.getAppFundRanking(WebUtils.getUserId(),startTime,endTime);
       }else{
           LocalDateTime now = appFundRankingMapper.time(2);
            String threshold = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(threshold, formatter);
            appFundRanking = appFundRankingMapper.getAppFundRankingDescWeek(WebUtils.getUserId(),threshold,dateTime.plusDays(7).toString());}
        if(Objects.isNull(appFundRanking)){
            appFundRanking = new AppFundRanking();
            appFundRanking.setUserId(WebUtils.getUserId());
            appFundRanking.setAmount(BigDecimal.ZERO);
        }

        return ApiResponse.create(appFundRanking);
    }



    @Resource
    AdminFundRankConfigMapper adminFundRankConfigMapper;

    @Resource
    AppFundV2InfoMapper appFundV2InfoMapper;

  @GetMapping ("/bouns")
    @NotAuthorization
    public ApiResponse dayBouns(@RequestParam("type")Integer type) {
        List<AppFundRanking> list;
        LocalDateTime now = LocalDateTime.now();
        String endTime = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";


        if(type.equals(1)){
            now = now.plusDays(-1);
            String startTime = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
             list = appFundRankingMapper.getAppFundRankingDesc1(startTime,endTime);
        }else {
            now = now.plusDays(-7);
            String startTime = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
             list = appFundRankingMapper.getAppFundRankingDesc7(startTime,endTime);
        }
        List<AdminFundRankConfig> list1 = adminFundRankConfigMapper.selectList(new QueryWrapper());
        AppFundRankInfo appFundRanking = appFundRankInfoMapper.getRankInfoForupdate();
        for (int i = 0; i < list.size(); i++) {
            AppFundRanking appFundRanking1 = list.get(i);
            if(type.equals(2)){
                appFundRanking1.setType(2);
                if(i>=list1.size()) {
                    appFundRanking1.update(new QueryWrapper<AppFundRanking>().eq("user_id",appFundRanking1.getUserId()));
                    continue;
                }
                appFundRanking1.update(new QueryWrapper<AppFundRanking>().eq("user_id",appFundRanking1.getUserId()));

                if(appMallAmbassadorMapper.getCountByUserAndLevel(appFundRanking1.getUserId())<=0){
                    appFundRanking1.update(new QueryWrapper<AppFundRanking>().eq("user_id",appFundRanking1.getUserId()));
                    continue;
                }
            }

            appFundRanking1.updateById();
            int finalI = i;
            AdminFundRankConfig adminFundRankConfig =  list1.stream().filter(l->l.getRanking().equals(finalI +1)).collect(Collectors.toList()).get(0);
            BigDecimal  money = appFundRanking.getDayAmount().multiply(adminFundRankConfig.getRate());

            AppFundV2Info  appFundV2Info = appFundV2InfoMapper.selectBYUserId(appFundRanking1.getUserId());
            if(org.springframework.util.ObjectUtils.isEmpty(appFundV2Info) || appFundV2Info.getRetained().compareTo(BigDecimal.ZERO) == 0){
                AppRankingDetail appRankingDetail = new AppRankingDetail();
                appRankingDetail.setRanking(i+1);
                appRankingDetail.setAmount(BigDecimal.ZERO);
                appRankingDetail.setType(type);
                appRankingDetail.setUserId(appFundRanking1.getUserId());
                appRankingDetail.setCreateTime(LocalDateTime.now());
                appRankingDetail.setPerformance(appFundRanking1.getAmount());
                appRankingDetail.setSumAmount(appFundRanking.getDayAmount());
                appRankingDetail.insert();
            }else {
                if(money.compareTo(appFundV2Info.getRetained()) > 0){
                    money = appFundV2Info.getRetained();
                }

                AppFundV2Info appFundV2Info1 = appFundInfoService.updateInfo(appFundRanking1.getUserId(),money,BigDecimal.ZERO);


                AppFundV2Detail appFundV2Detail = new AppFundV2Detail();
                appFundV2Detail.setAmount(money);
                appFundV2Detail.setUserId(appFundV2Info.getUserId());
                appFundV2Detail.setCreateTime(LocalDateTime.now());
                appFundV2Detail.setAfterAmount(appFundV2Info1.getRetained());
                appFundV2Detail.setType(11);
                appFundV2Detail.insert();

                Integer walletId = appUserWalletMapper.checkoutTokenIdAndUserId(LetokenTokenTypeEnum.LET.getId(),appFundRanking1.getUserId());
                if (ObjectUtils.isEmpty(walletId)){
                    continue;
                }
                AppUserWallet w = appUserWalletMapper.selectForUpdate(walletId);
                AppUserWallet updateW = new AppUserWallet();
                updateW.setId(w.getId());
                updateW.setAvailableBalance(w.getAvailableBalance().add(money));
                appUserWalletMapper.updateById(updateW);

                AppUserAssetsHistory assetHistory = new AppUserAssetsHistory();
                assetHistory.setUserId(appFundRanking1.getUserId());
                assetHistory.setType(TokenTransactionTypeEnum.DAY_BOUS.getValue());
                assetHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
                assetHistory.setTokenId(LetokenTokenTypeEnum.LET.getId());
                assetHistory.setAmount(money);
                assetHistory.setBalance(updateW.getAvailableBalance());
                assetHistory.setCreateTime(LocalDateTime.now());
                assetHistory.setUpdateTime(assetHistory.getCreateTime());
                appUserAssetsHistoryMapper.insert(assetHistory);

                AppRankingDetail appRankingDetail = new AppRankingDetail();
                appRankingDetail.setRanking(i+1);
                appRankingDetail.setAmount(money);
                appRankingDetail.setType(type);
                appRankingDetail.setUserId(appFundRanking1.getUserId());
                appRankingDetail.setCreateTime(LocalDateTime.now());
                appRankingDetail.setPerformance(appFundRanking1.getAmount());
                appRankingDetail.setSumAmount(appFundRanking.getDayAmount());
                appRankingDetail.insert();
                fundRelease(appFundRanking1.getUserId(),money);
            }

        }

        AppFundRankInfo appFundRanking1 = new AppFundRankInfo();
        if(type.equals(1)){
            appFundRanking1.setDayAmount(BigDecimal.ZERO);
        }else {
            appFundRanking1.setWeekAmout(BigDecimal.ZERO);
        }
        appFundRanking1.setUpdateTime(LocalDateTime.now());
        appFundRanking1.setId(1);
        appFundRankInfoMapper.updateById(appFundRanking1);
        return ApiResponse.create();
    }


    @GetMapping ("/weekBouns")
    @NotAuthorization
    public void weekBouns() {
        LocalDateTime now = LocalDateTime.now();
        String endTime = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
        now = now.plusDays(-7);
        String startTime = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";

        List<AppFundRanking> list = appFundRankingMapper.getAppFundRankingDesc7(startTime,endTime);
        List<AdminFundRankConfig> list1 = adminFundRankConfigMapper.selectList(new QueryWrapper());
        AppFundRankInfo appFundRanking = appFundRankInfoMapper.getRankInfoForupdate();
        if(appFundRanking.getWeekAmout().compareTo(BigDecimal.ZERO)<=0){
            appFundRanking.updateById();
            return;
        }

        for (int i = 0; i < list.size(); i++) {
            AppFundRanking appFundRanking1 = list.get(i);
            AppFundRanking appFundRanking2 = new AppFundRanking();
            appFundRanking2.setType(2);
            if(i>=list1.size()){
                appFundRanking2.update(new QueryWrapper<AppFundRanking>().eq("user_id",appFundRanking1.getUserId()));
                continue;
            }
            /*if(appMallAmbassadorMapper.getCountByUserAndLevel(appFundRanking1.getUserId())<=0){
                appFundRanking2.update(new QueryWrapper<AppFundRanking>().eq("user_id",appFundRanking1.getUserId()));
                continue;
            }*/
            int finalI = i;
            AdminFundRankConfig adminFundRankConfig =  list1.stream().filter(l->l.getRanking().equals(finalI +1)).collect(Collectors.toList()).get(0);
            BigDecimal  money = appFundRanking.getWeekAmout().multiply(adminFundRankConfig.getRate());


            AppFundV2Info  appFundV2Info = appFundV2InfoMapper.selectBYUserId(appFundRanking1.getUserId());
            if(org.springframework.util.ObjectUtils.isEmpty(appFundV2Info) || appFundV2Info.getRetained().compareTo(BigDecimal.ZERO) == 0){
                AppRankingDetail appRankingDetail = new AppRankingDetail();
                appRankingDetail.setRanking(i+1);
                appRankingDetail.setAmount(BigDecimal.ZERO);
                appRankingDetail.setType(2);
                appRankingDetail.setUserId(appFundRanking1.getUserId());
                appRankingDetail.setCreateTime(LocalDateTime.now());
                appRankingDetail.setPerformance(appFundRanking1.getAmount());
                appRankingDetail.setSumAmount(appFundRanking.getWeekAmout());
                appRankingDetail.insert();

            }else {
                if(money.compareTo(appFundV2Info.getRetained()) > 0){
                    money = appFundV2Info.getRetained();
                }

                AppFundV2Info appFundV2Info1 = appFundInfoService.updateInfo(appFundRanking1.getUserId(),money,BigDecimal.ZERO);


                AppFundV2Detail appFundV2Detail = new AppFundV2Detail();
                appFundV2Detail.setAmount(money);
                appFundV2Detail.setUserId(appFundV2Info.getUserId());
                appFundV2Detail.setCreateTime(LocalDateTime.now());
                appFundV2Detail.setAfterAmount(appFundV2Info1.getRetained());
                appFundV2Detail.setType(12);
                appFundV2Detail.insert();

                Integer walletId = appUserWalletMapper.checkoutTokenIdAndUserId(LetokenTokenTypeEnum.LET.getId(),appFundRanking1.getUserId());
                if (ObjectUtils.isEmpty(walletId)){
                    continue;
                }
                AppUserWallet w = appUserWalletMapper.selectForUpdate(walletId);
                AppUserWallet updateW = new AppUserWallet();
                updateW.setId(w.getId());
                updateW.setAvailableBalance(w.getAvailableBalance().add(money));
                appUserWalletMapper.updateById(updateW);

                AppUserAssetsHistory assetHistory = new AppUserAssetsHistory();
                assetHistory.setUserId(appFundRanking1.getUserId());
                assetHistory.setType(TokenTransactionTypeEnum.WEEK_BOUS.getValue());
                assetHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
                assetHistory.setTokenId(LetokenTokenTypeEnum.LET.getId());
                assetHistory.setAmount(money);
                assetHistory.setBalance(updateW.getAvailableBalance());
                assetHistory.setCreateTime(LocalDateTime.now());
                assetHistory.setUpdateTime(assetHistory.getCreateTime());
                appUserAssetsHistoryMapper.insert(assetHistory);
                appFundRanking2.update(new QueryWrapper<AppFundRanking>().eq("user_id",appFundRanking1.getUserId()));

                AppRankingDetail appRankingDetail = new AppRankingDetail();
                appRankingDetail.setRanking(i+1);
                appRankingDetail.setAmount(money);
                appRankingDetail.setType(2);
                appRankingDetail.setUserId(appFundRanking1.getUserId());
                appRankingDetail.setCreateTime(LocalDateTime.now());
                appRankingDetail.setPerformance(appFundRanking1.getAmount());
                appRankingDetail.setSumAmount(appFundRanking.getWeekAmout());
                appRankingDetail.insert();

                fundRelease(appFundRanking1.getUserId(),money);
            }

        }
        AppFundRankInfo appFundRanking1 = new AppFundRankInfo();
        appFundRanking1.setWeekAmout(BigDecimal.ZERO);
        appFundRanking1.setUpdateTime(LocalDateTime.now());
        appFundRanking1.setId(1);
        appFundRankInfoMapper.updateById(appFundRanking1);
    }

    @GetMapping ("/getBonus")
    public ApiResponse getBonus() {
        return ApiResponse.create(appFundRankInfoMapper.selectById(1));
    }

    @Resource
    private AppMallAmbassadorMapper appMallAmbassadorMapper;
   // @GetMapping ("/getUserData")
    public ApiResponse getUserData() {
       List<AppMallAmbassador> list = appMallAmbassadorMapper.selectList(new QueryWrapper<>());
     //  List<AppFundLevelInfo> levelInfos = new ArrayList<>();
        for (AppMallAmbassador appMallAmbassador: list) {
            AppFundLevelInfo appFundLevelInfo = new AppFundLevelInfo();
            appFundLevelInfo.setUserId(appMallAmbassador.getUserId());
            appFundLevelInfo.setLevel(appMallAmbassador.getLevel()>0?appMallAmbassador.getLevel()+5:appMallAmbassador.getLevel());
            appFundLevelInfo.setCreateTime(appMallAmbassador.getCreateTime());
            appFundLevelInfo.insertOrUpdate();

        }
        return ApiResponse.create();
    }

    @Resource
    private AdminFundLevelConfigMapper adminFundLevelConfigMapper;
    @Resource
    private AppUserTeamMapper appUserTeamMapper;

    @Resource
    private AdminFundDistributeConfigMapper adminFundDistributeConfigMapper;

    @GetMapping ("/addAmount")
    @NotAuthorization
    public void addAmount() {

        LocalDateTime now = LocalDateTime.now();
        String endTime = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
        now = now.plusDays(-1);
        String startTime = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";

        BigDecimal amount = adminFundConfigMapper.getFundBankList(startTime,endTime);
        BigDecimal day = BigDecimal.ZERO;
        BigDecimal week = BigDecimal.ZERO;;
        AdminFundDistributeConfig adminFundDistributeConfig = adminFundDistributeConfigMapper.selectById(1);

        day = day.add(amount.multiply(adminFundDistributeConfig.getDayRate()));
        week = week.add(amount.multiply(adminFundDistributeConfig.getWeekRate()));

        AppFundRankInfo appFundRankInfo = appFundRankInfoMapper.getRankInfoForupdate();

        AppFundRankInfo appFundRanking1 = new AppFundRankInfo();
        appFundRanking1.setWeekAmout(week.add(appFundRankInfo.getWeekAmout()));
        appFundRanking1.setDayAmount(day);
        appFundRanking1.setUpdateTime(LocalDateTime.now());
        appFundRanking1.setId(1);
        appFundRankInfoMapper.updateById(appFundRanking1);
    }

   // @GetMapping ("/updateUserData")
    //@NotAuthorization
    public ApiResponse updateUserData() {
        List<Integer> idList = appFundInfoMapper.getFundUser();
        List<AdminFundLevelConfig> levelConfigs = adminFundLevelConfigMapper.getLevelList();
        for (Integer id:idList) {
            AppUserTeam appUserTeam = appUserTeamMapper.selectById(id);

            if(appUserTeam != null && !appUserTeam.getInviterId().equals(0)){
                AppFundLevelInfo appFundLevelInfo =  appFundLevelInfoMapper.selectById(appUserTeam.getInviterId());

                if(appFundLevelInfo==null || appFundLevelInfo.getLevel()<6){
                    Integer count = appFundLevelInfoMapper.getFundByInviterIdCOunt(appUserTeam.getInviterId());
                    for (AdminFundLevelConfig adminFundLevelConfig:levelConfigs) {
                        if (count >= adminFundLevelConfig.getCondition()){
                            AppFundLevelInfo info = new AppFundLevelInfo();
                            info.setLevel(adminFundLevelConfig.getLevel());
                            info.setUserId(appUserTeam.getInviterId());
                            info.setUpdateTime(LocalDateTime.now());
                            info.setCreateTime(LocalDateTime.now());
                            info.insertOrUpdate();
                            break;
                        }
                    }
                }
            }
        }
        return ApiResponse.create();
    }

    @Autowired
    private AppFundDetailService appFundDetailService;

    @Resource
    AppUserAssetsHistoryMapper appUserAssetsHistoryMapper;


    @Autowired
    RabbitTemplate rabbitTemplate;

   @GetMapping ("/test")
    @NotAuthorization
    public  ApiResponse test() {
       appFundV2InfoService.income();
        return ApiResponse.create();
    }
    /*public void queueBonus(Integer userId,BigDecimal amount){

        FundConsumer.BonusDto dto = new FundConsumer.BonusDto();
        dto.setAmount(amount);
        dto.setUserId(userId);
        rabbitTemplate.convertAndSend(FundConsumer.exchange, FundConsumer.queueBonus,  JSONObject.toJSON(dto).toString());
    }*/

    public void queueWeighting(BigDecimal amount){
        rabbitTemplate.convertAndSend(FundConsumer.exchange, FundConsumer.queueWeighting, amount);
    }


    /*@GetMapping ("/update")
    @NotAuthorization*/
    public  void update() {
        List<Integer> fundUserIdList= appFundInfoMapper.getupdateFundUserId();
        BigDecimal bigDecimal = BigDecimal.ZERO;
        List<AdminFundConfig> configList = adminFundConfigMapper.selectList(new QueryWrapper<>());
        for (Integer userId:fundUserIdList) {
            List<AppFundInfo> infoList = appFundInfoMapper.getupdateFundByUserId(userId);
            //给上级带来奖励的总额
            BigDecimal  award = BigDecimal.ZERO;
            for (AppFundInfo appFundInfo:infoList) {
                BigDecimal rate = configList.stream().filter(s->s.getId().equals(appFundInfo.getFundId())).collect(Collectors.toList()).get(0).getRate();
                appFundInfo.setAmount(appFundInfo.getFund().multiply(rate));
                // sumFund = sumFund.add(appFundInfo.getAmount());
                if(appFundInfo.getState().equals(1)){
                    award = award.add(appFundInfo.getAmount());
                }
            }
            //  给所有等级奖励总额
            bigDecimal = bigDecimal.add(award);
            queueBonus(userId,award);
        }

    }

    @Autowired
    private AppUserAssetsHistoryService appUserAssetsHistoryService;

    public void queueBonus(Integer userId,BigDecimal money) {

            FundConsumer.BonusDto dto =new FundConsumer.BonusDto();
            dto.setAmount(money);
            dto.setUserId(userId);
            BigDecimal amount = dto.getAmount();
            BigDecimal rate =  appFundInfoMapper.getMaxfundRate();
            List<UserLevelReq> list = appFundInfoMapper.selectUserLevel(dto.getUserId());
            Integer level = 0;
            BigDecimal levelRate = BigDecimal.ZERO;
            List<AdminFundLevelConfig> configList = adminFundLevelConfigMapper.getList();
            if(list.size()>0){
                for (UserLevelReq req:list) {
                    BigDecimal bigDecimal;
                    if(req.getLevel()<6){
                        bigDecimal = appFundInfoMapper.sumAmount(req.getUserId(),1);
                    }else {
                        bigDecimal = appFundInfoMapper.sumAmount(req.getUserId(),3);
                    }
                    if(req.getLevel() > level && rate.compareTo(BigDecimal.ZERO) > 0){
                        BigDecimal rates= req.getRate();
                        req.setRate(req.getRate().subtract(levelRate));
                        BigDecimal ss = rate.compareTo(req.getRate())>0?req.getRate():rate;
                        BigDecimal reward = amount.multiply(ss);
                        rate = rate.compareTo(req.getRate())>0?rate.subtract(req.getRate()):BigDecimal.ZERO;
                        level = req.getLevel();
                        levelRate = rates;
                        BigDecimal sss = configList.stream().filter(s->s.getLevel().equals(req.getLevel())).collect(Collectors.toList()).get(0).getFundAmount();
                        if(bigDecimal.compareTo(sss)<0)continue;


                        AppFundDetail appFundDetail = new AppFundDetail();
                        appFundDetail.setUserId(req.getUserId());
                        appFundDetail.setType(2);
                        appFundDetail.setAmount(reward);
                        appFundDetail.setCreateTime(LocalDateTime.now());
                        appFundDetail.insert();
                        int updateWallet = appUserWalletService.updateUserAmountByUserIDandCoin(reward, new BigDecimal("0"),BigDecimal.ZERO, req.getUserId(), LetokenTokenTypeEnum.LET.getId());
                        if (updateWallet == 0) {
                            throw new ApiServiceException(500, "mint失败，请稍后再试！");
                        }

                        AppUserAssetsHistory appUserAssetsHistory = new AppUserAssetsHistory();
                        appUserAssetsHistory.setUserId(req.getUserId());
                        appUserAssetsHistory.setType(TokenTransactionTypeEnum.FUND_BONUS.getValue());
                        appUserAssetsHistory.setStatus(1);
                        appUserAssetsHistory.setSn(req.getUserId().toString());
                        appUserAssetsHistory.setTokenId(2);
                        appUserAssetsHistory.setAmount(reward);
                        appUserAssetsHistory.setCreateTime(LocalDateTime.now());
                        appUserAssetsHistory.setUpdateTime(LocalDateTime.now());
                        try {
                            appUserAssetsHistory.setBalance(appUserWalletMapper.getAvailableBalance(appUserAssetsHistory.getTokenId(),appUserAssetsHistory.getUserId()));
                        }catch (Exception e){
                            log.error("查询余额失败 tokenId {" +appUserAssetsHistory.getTokenId()+ "} userId {"+appUserAssetsHistory.getUserId()+"} eMsg {"+ e.getMessage()+"}");
                        }
                        boolean saveHistory = appUserAssetsHistoryService.save(appUserAssetsHistory);
                        if (!saveHistory) {
                            throw new ApiServiceException(500, "mint失败，请稍后再试！");
                        }
                    }
                }
            }

    }


    @GetMapping ("/getUserLamp")
    public ApiResponse getUserLamp() {
       Integer userId = WebUtils.getUserId();
       AppUserLamp appUserLamp = appUserLampService.getById(userId);
       if(ObjectUtils.isNotEmpty(appUserLamp)){
           List<AppUserLamp> list = appUserLampMapper.getLampList(userId);
           if (org.springframework.util.ObjectUtils.isEmpty(list) || list.size() <= 1) {
               appUserLamp.setTeamPerformance(BigDecimal.ZERO);
           }else{
               appUserLamp.setTeamPerformance(list.get(1).getTeamPerformance());
           }
           if(list.size()>2){
               appUserLamp.setTwoTeamPerformance(list.get(2).getTeamPerformance());
           }else {
               appUserLamp.setTwoTeamPerformance(BigDecimal.ZERO);
           }
           appUserLamp.setAdminLampConfigs(adminLampConfigMapper.getLampConfigLists());
       } else  {
           appUserLamp = new AppUserLamp();
           appUserLamp.setAdminLampConfigs(adminLampConfigMapper.getLampConfigLists());

       }
        return ApiResponse.create(appUserLamp);
    }


    @GetMapping ("/getRankConfig")
    public ApiResponse<AdminFundRankConfig> getRankConfig() {
        return ApiResponse.create(adminFundRankConfigMapper.selectList(new QueryWrapper<>()));
    }

    @Resource
    AppRankingDetailMapper appRankingDetailMapper;
    @GetMapping ("/yesterdayGetRankConfig")
    public ApiResponse<Map<String,Object>> yesterdayGetRankConfig(@RequestParam("type")Integer type) {
        Map<String,Object> map = new HashMap<>();
       List<AppRankingDetail> list1  =new ArrayList<>();
        if(type.equals(1)){
            LocalDateTime endTime =  appFundRankingMapper.time(1);
            list1 = appRankingDetailMapper.getDetail(1);
            map.put("currentUser",appFundRankingMapper.getAppFundRanking(WebUtils.getUserId(),endTime.plusDays(-1).toString(),endTime.toString()));
           // map.put("currentUser",appFundRankingMapper.yesterdayAppFundRanking1(WebUtils.getUserId()));
        }else {
            LocalDateTime endTime =  appFundRankingMapper.time(2);
            list1 = appRankingDetailMapper.getDetail(2);
            map.put("currentUser",appFundRankingMapper.getAppFundRanking(WebUtils.getUserId(),endTime.plusDays(-7).toString(),endTime.toString()));
           // map.put("currentUser",appFundRankingMapper.yesterdayAppFundRanking7(WebUtils.getUserId()));
        }
        map.put("sumAmount",list1.get(0).getSumAmount());
        map.put("rank",list1);
        return ApiResponse.create(map);
    }


    @GetMapping ("/next")
    public ApiResponse<Map<String,Object>> next() {
        LocalDateTime now = LocalDateTime.now();
        Map<String,Object> map = new HashMap<>();

        String threshold = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(threshold, formatter);

        if(now.isAfter(dateTime) == true){
            now = now.plusDays(1);
            map.put("day",now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00");
        }else{
            map.put("day",now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 18:00:00");
        }


        map.put("week",appFundRankingMapper.next7());
        map.put("now",LocalDateTime.now());
        return ApiResponse.create(map);
    }

    public void fundRelease(Integer userId,BigDecimal amount){
        FundReleaseConsumer.FundReleaseDto dto = new FundReleaseConsumer.FundReleaseDto();
        dto.setAmount(amount.negate());
        dto.setUserId(userId);
        rabbitTemplate.convertAndSend( FundReleaseConsumer.queue,  JSONObject.toJSON(dto).toString());
    }
    @GetMapping ("/lamd")
    @NotAuthorization
    public  void lamd() {
        appUserLampService.lamd();
    }
}

